package com.tf_cut.backend.agent.mobile.controller;

import com.tf_cut.backend.agent.mobile.vo.SellerOrderProviderResultVo;
import com.tf_cut.backend.agent.mobile.vo.SellerOrderProviderVo;
import com.tf_cut.backend.agent.service.AgentAccountService;
import com.tf_cut.backend.agent.service.AgentAndAccountService;
import com.tf_cut.backend.agent.service.AgentSellerRelationService;
import com.tf_cut.backend.agent.service.AgentService;
import com.tf_cut.backend.agent.vo.AgentAndAccountVo;
import com.tf_cut.backend.common.pojo.PageInfo;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.seller.service.*;
import com.tf_cut.backend.seller.vo.SellerAndAccountVo;
import com.tf_cut.backend.seller.vo.SellerOrderVo;
import com.tf_cut.backend.seller.vo.SellerRefAgentVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/backend/agent/mobile/seller")
public class AgentMobileSellerController {

    @Autowired
    private SellerAndAccountService sellerAndAccountService;


    @Autowired
    private SellerRefAgentService sellerRefAgentService;


    @Autowired
    private SellerService sellerService;

    @Autowired
    private AgentAccountService agentAccountService;

    @Autowired
    private AgentAndAccountService agentAndAccountService;

    @Autowired
    private AgentSellerRelationService agentSellerRelationService;

    @Autowired
    private AgentService agentService;

    // 根据代理商查商户
    @GetMapping("/findsellerWithAgentId")
    public Result<List<SellerAndAccountVo>> findsellerWithAgentId(@RequestParam String agentId) {
        Result<List<SellerAndAccountVo>> result=null;
        try {

            List<SellerAndAccountVo> sellerWithAgentId = sellerAndAccountService.findSellerWithAgentId(agentId);


            result=Result.of(sellerWithAgentId);

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(new ArrayList<>());
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }

        return result;

    }


    // 根据代理商查商户
    @GetMapping("/sellerlistWithAgentId")
    public Result<PageInfo<SellerAndAccountVo>> findListSeller(@RequestParam String agentId,@RequestParam(required = false) String agentName, @RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int rows) {
        //其实是sellerName
        if(StringUtils.isBlank(agentName))
            agentName=null;
        Result<PageInfo<SellerAndAccountVo>> result=null;
        try {

            AgentAndAccountVo data = this.agentService.get(agentId).getData();
            List<String> agentIds=new ArrayList<>();
            agentIds.add(data.getAgentId());
            //如果等于0 代表一级代理商
            if(data.getParentAgentId().equals("0")) {
                List<AgentAndAccountVo> data1 = this.agentService.list(AgentAndAccountVo.builder()
                        .parentAgentId(data.getAgentId()).build()).getData();
                if (data1.size() > 0) {
                    agentIds.addAll(data1.stream().map(e -> e.getAgentId()).collect(Collectors.toList()));
                }
            }

            //查询出对应的商户
            SellerRefAgentVo svo = SellerRefAgentVo.builder().agentIds(agentIds).sellerName(agentName).build();
            svo.setPage(page);
            svo.setRows(rows);
            PageInfo<SellerRefAgentVo> listSellerRefAgent = sellerRefAgentService.findListSellerRefAgent(svo);

            //查询商户信息
            PageInfo<SellerAndAccountVo> resultpageinfo=new PageInfo<>();
            resultpageinfo.setPage(listSellerRefAgent.getPage());
            resultpageinfo.setPageSize(listSellerRefAgent.getPageSize());
            resultpageinfo.setRecords(listSellerRefAgent.getRecords());
            resultpageinfo.setTotal(listSellerRefAgent.getTotal());
            if(!listSellerRefAgent.getRows().isEmpty()){

                List<SellerRefAgentVo> rows1 = listSellerRefAgent.getRows();

                List<String> sellerids =rows1 .stream().map(e -> e.getSellerId()).collect(Collectors.toList());
                List<SellerAndAccountVo> sellerAndAccountVos = this.sellerAndAccountService.findListWithSellerIds(sellerids,null);

                Map<String, List<SellerRefAgentVo>> collect = rows1.stream().collect(Collectors.groupingBy(SellerRefAgentVo::getSellerId));

                for(SellerAndAccountVo bean:sellerAndAccountVos){

                    if(collect!=null&&collect.containsKey(bean.getSellerId())){
                        SellerRefAgentVo sellerRefAgentVo = collect.get(bean.getSellerId()).get(0);
                        bean.setServerAmount(sellerRefAgentVo.getServerAmountPoint());
                        bean.setAgentName(sellerRefAgentVo.getAgentName());
                        bean.setParentAgentId(sellerRefAgentVo.getParentAgentId());
                    }
                }
                resultpageinfo.setRows(sellerAndAccountVos);
            }

            result=Result.of(resultpageinfo);

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(new PageInfo<>());
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }

        return result;

    }

    // 根据代理商查商户
    @GetMapping("/sellerDetail")
    public Result<SellerAndAccountVo> sellerDetail(@RequestParam String sellerId) {
        Result<SellerAndAccountVo> result=null;
        try {
            //查询出对应的商户
            result = sellerService.get(sellerId);

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(SellerAndAccountVo.builder().build());
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }

        return result;

    }


    @PostMapping("/sellerAmountWithAgentId")
    public Result<List<SellerOrderProviderVo>> sellerAmountWithAgentId(@RequestBody SellerOrderProviderVo sellerOrderProviderVo) {
        Result<List<SellerOrderProviderVo>> result=null;
        try {

//            AgentAndAccountVo data = this.agentService.get(sellerOrderProviderVo.getAgentId()).getData();
//            List<String> agentIds=new ArrayList<>();
//            agentIds.add(data.getAgentId());
//            //如果等于0 代表一级代理商
//            if(data.getParentAgentId().equals("0")) {
//                List<AgentAndAccountVo> data1 = this.agentService.list(AgentAndAccountVo.builder()
//                        .parentAgentId(data.getAgentId()).build()).getData();
//                if (data1.size() > 0) {
//                    agentIds.addAll(data1.stream().map(e -> e.getAgentId()).collect(Collectors.toList()));
//                }
//            }
//
//            //查询
//            List<AgentAndAccountVo> agentAccountwithagentIds = agentAndAccountService.findAgentAccountwithagentIds(agentIds);
//            List<String> agentAccountIds = agentAccountwithagentIds.stream().map(e -> e.getAgentAccountId()).collect(Collectors.toList());
//
            List<String> agentIds=new ArrayList<>();
            agentIds.add(sellerOrderProviderVo.getAgentId());
            List<AgentAndAccountVo> agentAccountwithagentIds = agentAndAccountService.findAgentAccountwithagentIds(agentIds);

            sellerOrderProviderVo.setAgentAccountId(agentAccountwithagentIds.get(0).getAgentAccountId());

            if(StringUtils.isBlank(sellerOrderProviderVo.getSellerName())){
                sellerOrderProviderVo.setSellerName(null);
            }

            List<SellerOrderProviderVo> sellerOrderProviderVos = sellerAndAccountService.sellerAmountWithAgentId(sellerOrderProviderVo);
            List<String> sellerids = sellerOrderProviderVos.stream().map(e -> e.getSellerId()).collect(Collectors.toList());
            if(!sellerids.isEmpty()){
                List<AgentAndAccountVo> listAgent = this.agentSellerRelationService.findListAgent(sellerids);
                if(!CollectionUtils.isEmpty(listAgent)){
                    Map<String, List<AgentAndAccountVo>> collect = listAgent.stream().collect(Collectors.groupingBy(AgentAndAccountVo::getSellerId));
                    sellerOrderProviderVos.forEach(e->{
                        if(collect.containsKey(e.getSellerId())&&collect.get(e.getSellerId())!=null){
                            e.setAgentName(collect.get(e.getSellerId()).get(0).getAgentName());
                            e.setParentAgentId(collect.get(e.getSellerId()).get(0).getParentAgentId());
                            e.setAgentId(collect.get(e.getSellerId()).get(0).getAgentId());
                        }

                    });

                }
            }
            result=Result.of(sellerOrderProviderVos);


        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(null);
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }

        return result;

    }

    @PostMapping("/sellerProviderDay")
    public Result<SellerOrderProviderResultVo> sellerProviderDay(@RequestBody SellerOrderProviderVo sellerOrderProviderVo) {
        Result<SellerOrderProviderResultVo> result=null;
        try {
            //查询出对应的商户
            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(sellerOrderProviderVo.getAgentId());
            sellerOrderProviderVo.setAgentAccountId(agentAndAccountVo.getAgentAccountId());
            List<SellerOrderProviderVo> sellerOrderProviderVos = sellerAndAccountService.sellerProviderDay(sellerOrderProviderVo);

            Result<AgentAndAccountVo> agentAndAccountVoResult = this.agentService.get(sellerOrderProviderVo.getAgentId());

            SellerOrderProviderResultVo sellerOrderProviderResultVo = SellerOrderProviderResultVo.builder().vos(sellerOrderProviderVos).build();


            if(agentAndAccountVoResult!=null&&agentAndAccountVoResult.isFlag()){
                BeanUtils.copyProperties(agentAndAccountVoResult.getData(), sellerOrderProviderResultVo);
            }

            result=Result.of(sellerOrderProviderResultVo);


        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(null);
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }

        return result;

    }


    @PostMapping("/sellerProviderMonth")
    public Result<SellerOrderProviderResultVo> sellerProviderMonth(@RequestBody SellerOrderProviderVo sellerOrderProviderVo) {
        Result<SellerOrderProviderResultVo> result=null;
        try {
            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(sellerOrderProviderVo.getAgentId());
            sellerOrderProviderVo.setAgentAccountId(agentAndAccountVo.getAgentAccountId());
            //查询出对应的商户
            String month = sellerOrderProviderVo.getMonth();
            SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM");




            //本月总收入 和总支出
            //本月第一天和最后一天
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(format1.parse(month));
            c.set(Calendar.DAY_OF_MONTH,c.getActualMinimum(Calendar.DAY_OF_MONTH));//1:本月第一天
            String startDate= format.format(c.getTime());

            Calendar ca = Calendar.getInstance();
            ca.setTime(format1.parse(month));
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String endDate= format.format(ca.getTime());

            sellerOrderProviderVo.setStartDate(startDate);
            sellerOrderProviderVo.setEndDate(endDate);
            List<SellerOrderProviderVo> sellerOrderProviderVos = sellerAndAccountService.sellerProviderDay(sellerOrderProviderVo);

            Result<AgentAndAccountVo> agentAndAccountVoResult = this.agentService.get(sellerOrderProviderVo.getAgentId());

            SellerOrderProviderResultVo sellerOrderProviderResultVo = SellerOrderProviderResultVo.builder().vos(sellerOrderProviderVos).build();


            if(agentAndAccountVoResult!=null&&agentAndAccountVoResult.isFlag()){
                BeanUtils.copyProperties(agentAndAccountVoResult.getData(), sellerOrderProviderResultVo);
            }

            result=Result.of(sellerOrderProviderResultVo);

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(null);
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }

        return result;

    }

}
